import React, { useState } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  Modal,
  TextInput,
  Alert,
} from 'react-native';
import { colors, shadows, spacing } from '../../styles';
import Icon from '../../components/Icon';
import { useDeck } from './DeckContext';
import { Deck } from './types';

interface DeckListProps {
  onDeckReview: (deck: Deck) => void;
  onDeckManage: (deck: Deck) => void;
}

const DeckList: React.FC<DeckListProps> = ({ onDeckReview, onDeckManage }) => {
  const { decks, addDeck, deleteDeck, getDueCards } = useDeck();
  const [modalVisible, setModalVisible] = useState(false);
  const [deckName, setDeckName] = useState('');
  const [deckDescription, setDeckDescription] = useState('');
  const [addType, setAddType] = useState<'deck' | 'card'>('deck');

  const handleAddDeck = () => {
    if (deckName.trim()) {
      addDeck(deckName.trim(), deckDescription.trim() || undefined);
      setDeckName('');
      setDeckDescription('');
      setModalVisible(false);
    } else {
      Alert.alert('提示', '请输入卡牌组名称');
    }
  };

  const handleDeleteDeck = (deckId: string, deckName: string) => {
    Alert.alert('确认删除', `确定要删除卡牌组 "${deckName}" 吗？`, [
      { text: '取消', style: 'cancel' },
      {
        text: '删除',
        style: 'destructive',
        onPress: () => deleteDeck(deckId),
      },
    ]);
  };

  const renderDeckItem = ({ item }: { item: Deck }) => {
    const dueCards = getDueCards(item.id);
    const totalCards = item.cards.length;

    return (
      <View style={styles.deckItem}>
        <TouchableOpacity
          style={styles.deckInfo}
          onPress={() => onDeckReview(item)}
          onLongPress={() => handleDeleteDeck(item.id, item.name)}
        >
          <Text style={styles.deckName}>{item.name}</Text>
          {item.description && (
            <Text style={styles.deckDescription}>{item.description}</Text>
          )}
          <View style={styles.statsRow}>
            <Text style={styles.statsText}>
              总卡片: {totalCards} | 待复习: {dueCards.length}
            </Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.manageButton}
          onPress={() => onDeckManage(item)} // 点击管理图标也跳转到DeckDetail页面
        >
          <Icon name="settings" size={20} color={colors.primary} />
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={decks}
        renderItem={renderDeckItem}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>还没有卡牌组</Text>
            <Text style={styles.emptyHint}>点击右下角 + 按钮创建</Text>
          </View>
        }
      />

      {/* 悬浮按钮 */}
      <TouchableOpacity
        style={styles.fab}
        onPress={() => {
          setAddType('deck');
          setModalVisible(true);
        }}
      >
        <Text style={styles.fabText}>+</Text>
      </TouchableOpacity>

      {/* 添加卡牌组模态框 */}
      <Modal
        visible={modalVisible}
        transparent
        animationType="fade"
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>新建卡牌组</Text>

            <TextInput
              style={styles.input}
              placeholder="卡牌组名称"
              placeholderTextColor={colors.text.secondary}
              value={deckName}
              onChangeText={setDeckName}
            />

            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="描述（可选）"
              placeholderTextColor={colors.text.secondary}
              value={deckDescription}
              onChangeText={setDeckDescription}
              multiline
              numberOfLines={3}
            />

            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={[styles.button, styles.cancelButton]}
                onPress={() => {
                  setModalVisible(false);
                  setDeckName('');
                  setDeckDescription('');
                }}
              >
                <Text style={styles.cancelButtonText}>取消</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, styles.confirmButton]}
                onPress={handleAddDeck}
              >
                <Text style={styles.confirmButtonText}>创建</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  listContent: {
    padding: spacing.padding.md,
  },
  deckItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    backgroundColor: colors.surface,
    padding: spacing.padding.md,
    marginBottom: spacing.margin.md,
    borderRadius: 12,
    ...shadows.md,
  },
  deckInfo: {
    flex: 1,
  },
  deckName: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text.primary,
    marginBottom: 4,
  },
  deckDescription: {
    fontSize: 14,
    color: colors.text.secondary,
    marginBottom: 8,
  },
  statsRow: {
    flexDirection: 'row',
  },
  statsText: {
    fontSize: 12,
    color: colors.text.secondary,
  },
  arrowIcon: {
    transform: [{ rotate: '180deg' }],
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 100,
  },
  emptyText: {
    fontSize: 18,
    color: colors.text.secondary,
    marginBottom: 8,
  },
  emptyHint: {
    fontSize: 14,
    color: colors.text.secondary,
  },
  fab: {
    position: 'absolute',
    right: 20,
    bottom: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    ...shadows.lg,
  },
  fabText: {
    fontSize: 32,
    color: '#fff',
    fontWeight: '300',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    width: '85%',
    backgroundColor: colors.surface,
    borderRadius: 16,
    padding: 24,
    ...shadows.lg,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: colors.text.primary,
    marginBottom: 20,
    textAlign: 'center',
  },
  input: {
    backgroundColor: colors.background,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: colors.text.primary,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: colors.border.primary,
  },
  textArea: {
    height: 80,
    textAlignVertical: 'top',
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 12,
  },
  button: {
    flex: 1,
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
  },
  cancelButton: {
    backgroundColor: colors.background,
    marginRight: 8,
  },
  confirmButton: {
    backgroundColor: colors.primary,
    marginLeft: 8,
  },
  cancelButtonText: {
    color: colors.text.primary,
    fontSize: 16,
    fontWeight: '500',
  },
  confirmButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  manageButton: {
    padding: 8,
  },
});

export default DeckList;
